﻿namespace PrismEx.Modules.NavigationService
{
    using System.ComponentModel.Composition;

    using Microsoft.Practices.Prism.Events;
    using Microsoft.Practices.Prism.MefExtensions.Modularity;
    using Microsoft.Practices.Prism.Modularity;
    using Microsoft.Practices.Prism.Regions;

    using PrismEx.Events;
    using PrismEx.Events.Navigation;

    [ModuleExport(typeof(NavigationServiceModule))]
    public class NavigationServiceModule : IModule 
    {
        private readonly IEventAggregator eventAggregator;

        private readonly IRegionManager regionManager;

        [ImportingConstructor]
        public NavigationServiceModule(IEventAggregator eventAggregator, IRegionManager regionManager)
        {
            this.eventAggregator = eventAggregator;
            this.regionManager = regionManager;
        }

        public void Initialize()
        {
            this.eventAggregator.Subscribe<NavigateUriEvent>(this.NavigateUri);
            this.eventAggregator.Subscribe<InjectInstanceIntoRegionEvent>(this.InjectInstanceIntoRegion);
        }

        private void InjectInstanceIntoRegion(InjectInstanceIntoRegionEvent obj)
        {
            this.regionManager.AddToRegion(obj.RegionName, obj.Instance);
        }

        public void NavigateUri(NavigateUriEvent ev)
        {
            this.regionManager.RequestNavigate(ev.RegionName, ev.Uri);
        }
    }
}